<?php
//数据 trait
namespace App\Library\Traits;
use PDO;  // 这里引入内置的 PDO 类
trait DatabaseOperations
{
    /**
     * 插入数据
     *
     * @param string $table 表名
     * @param array $data 数据数组，键名为字段，键值为字段值
     * @return bool 成功返回 true，否则返回 false
     */
    public function insert($table, $data)
    {
        $fields = implode(", ", array_keys($data));
        $placeholders = ":" . implode(", :", array_keys($data));
        $sql = "INSERT INTO $table ($fields) VALUES ($placeholders)";
        
        return $this->executeQuery($sql, $data);
    }

    /**
     * 更新数据
     *
     * @param string $table 表名
     * @param array $data 更新的数据
     * @param array $conditions 更新条件
     * @return bool
     */
    public function update($table, $data, $conditions)
    {
        $setClause = implode(", ", array_map(fn($field) => "$field = :$field", array_keys($data)));
        $whereClause = $this->buildWhereClause($conditions);
        $sql = "UPDATE $table SET $setClause $whereClause";
        
        return $this->executeQuery($sql, array_merge($data, $conditions));
    }

    /**
     * 删除数据
     *
     * @param string $table 表名
     * @param array $conditions 删除条件
     * @return bool
     */
    public function delete($table, $conditions)
    {
        $whereClause = $this->buildWhereClause($conditions);
        $sql = "DELETE FROM $table $whereClause";
        
        return $this->executeQuery($sql, $conditions);
    }

    /**
     * 查询数据
     *
     * @param string $table 表名
     * @param array $conditions 查询条件
     * @param string $columns 要查询的列
     * @return array 查询结果
     */
    public function select($table, $conditions = [], $columns = "*")
    {
        $where = $this->buildWhereClause($conditions);
        $sql = "SELECT $columns FROM $table $where";
        
        return $this->executeQuery($sql, $conditions)->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * 构建查询条件部分
     *
     * @param array $conditions 条件数组
     * @return string SQL 的 WHERE 子句
     */
    private function buildWhereClause($conditions)
    {
        if (empty($conditions)) return "";
        
        $where = "WHERE " . implode(" AND ", array_map(fn($field) => "$field = :$field", array_keys($conditions)));
        return $where;
    }

    /**
     * 执行 SQL 查询
     *
     * @param string $sql SQL 查询语句
     * @param array $params 查询参数
     * @return \PDOStatement
     * @throws \Exception
     */
    private function executeQuery($sql, $params)
    {
        try {
            $stmt = $this->getConnection()->prepare($sql);
            $stmt->execute($params);
            return $stmt;
        } catch (PDOException $e) {
            error_log("Database query error: " . $e->getMessage());
            throw new Exception("Query execution failed: " . $e->getMessage());
        }
    }
}

